"""
Case Type   : 事务-ustore
Case Name   : 空事务提交/回滚->kill数据库
Create At   : 2022/1/14
Owner       : @kyleze
Description :
    1.空事务回滚
    2.kill数据库
    3.空事务提交
    4.kill数据库
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""
import os
import sys
import unittest

from yat.test import macro
from yat.test import Node

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class USTORE(unittest.TestCase):
    def setUp(self):
        self.pri_user = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.log = Logger()
        text = f'---{os.path.basename(__file__)} start---'
        self.log.info(text)
    
    def testunit_1(self):
        text = '----step1:空事务回滚;expect:成功----'
        self.log.info(text)
        q_str = f'''start transaction;rollback'''
        self.log.info(q_str)
        q_res = self.pri_sh.execut_db_sql(q_str)
        self.log.info(q_res)
        self.assertNotIn('ERROR', q_res, '执行失败: ' + text)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG, q_res,
                      '执行失败: ' + text)
        self.assertIn('ROLLBACK', q_res, '执行失败: ' + text)

        text = '----step2:kill-重启数据库;expect:成功----'
        self.log.info(text)
        result = self.pri_sh.restart_db_cluster()
        self.log.info(result)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue('Degraded' in status or 'Normal' in status)

        text = '----step3:空事务提交;expect:成功----'
        self.log.info(text)
        q_str = f'''start transaction;commit'''
        self.log.info(q_str)
        q_res = self.pri_sh.execut_db_sql(q_str)
        self.log.info(q_res)
        self.assertNotIn('ERROR', q_res, '执行失败: ' + text)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG, q_res,
                      '执行失败: ' + text)
        self.assertIn('COMMIT', q_res, '执行失败: ' + text)

        text = '----step4:kill-重启数据库;expect:成功----'
        self.log.info(text)
        result = self.pri_sh.restart_db_cluster()
        self.log.info(result)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue('Degraded' in status or 'Normal' in status)

    def tearDown(self):
        text = f'---{os.path.basename(__file__)} end---'
        self.log.info(text)
